package de.koller.million.card;

import de.koller.million.card.engine.CEngine;
import de.koller.million.card.frame.CMainFrame;
import de.koller.million.card.frame.util.NewsModel;
import de.koller.aframe.util.thread.ICommand;
import de.koller.oceanFramework.tree.Child;
import de.koller.oceanFramework.tree.Sea3X;
import de.koller.oceanFramework.util.MIn;
import de.koller.oceanFramework.util.MOut;
import java.io.File;
import java.util.Random;

public class CardRoot extends Sea3X {
	
	public final Random rnd = new Random();
	private final CLoop loop = new CLoop( this );
	
	@Child public final CEngine engine = new CEngine();
	@Child public final CMainFrame mainFrame = new CMainFrame();
	
	private long time = 0;

	private int nextPlayerID = 0;
	private long nextItemID = 0;
	
	public final NewsModel news = new NewsModel( 100 );
	
	@Override
	protected void init() {
		super.init();
		
		this.setIgnoreChildRender( true );
		
		//news.publish( new TextNewsEntry( time, "Wilkommen in " + CardStart.TITLE ) );
	}

	@Override
	protected void postChildInit() {
		super.postChildInit();
		
		this.load();
	}

	
	private void load() {
		MIn i = new MIn( "./cardData/realm.cnode" );
		time = i.readLong( 1 )[0];
		nextPlayerID = i.readInt( 1 )[0];
		nextItemID = i.readLong( 1 )[0];
		engine.playerContainer.load( i );
		i.close();
	}
	
	@Override
	protected void release() {
		super.release();
		save();
	}

	public void save() {
		File backup = new File( "./cardData/backup/" );
		if( !backup.exists() )
			backup.mkdirs();
		
		File old = new File( "./cardData/realm.cnode" );
		if( old.exists() )
			old.renameTo( new File( "./cardData/backup/backup_" + System.currentTimeMillis() + ".cnode" ) );
		
		MOut o = new MOut( "./cardData/realm.cnode" );
		o.writeLong( time );
		o.writeInt( nextPlayerID );
		o.writeLong( nextItemID );
		engine.playerContainer.save( o );
		o.close();
		
		System.out.println( "saved" );
	}
	
	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
		
		time++;
	}
	
	public void skipLoops( int loops ) {
		loop.setRunExtraSteps( loops );
	}
	
	public void start() {
		loop.begin();
	}
	
	public void stop() {
		loop.stop();
	}

	public void call( ICommand command ) {
		loop.thread.call( command );
	}

	public long getTime() {
		return time;
	}
	
	public int generatePlayerID() {
		int r = nextPlayerID;
		nextPlayerID++;
		return r;
	}
	
	public long generateItemID() {
		long r = nextItemID;
		nextItemID++;
		return r;
	}

}
